import { Col, Form, Input, message, TreeSelect, Select } from 'antd';
import React, { Fragment, useEffect } from 'react';
import { getFlowOrgTreeByOrgIDService, getUserDataList } from '@/services/BaseLayout';
import pageStyles from '@/common/pageLayout.less';
import { commonDeptGetUser, getUserID, getPosIDs } from '@/utils';
import MyIcon from '@/components/MyIcon';

export const UpdateAssignDept: React.FC<DelegateManageAPI.IUpdateAssignDeptView> = ({
  formRef,
  detailInfo,
  treeSearch,
  treeSearchValue,
  changeAssignUser,
  agentUserID,
}) => {
  /**获取组织机构树 接口 */
  const { getFlowOrgTreeRun, getFlowOrgTreeLoading, getFlowOrgList } = getFlowOrgTreeByOrgIDService();
  const { getUserRun, getUserLoading, getUserList } = getUserDataList((res: any) => {
    if (!(res && res?.msgFlag)) {
      message.error(res?.msg);
    }
  });

  /** 初始化 */
  useEffect(() => {
    let deptParams = {
      params: 0,
      flowType: 1,
      orgID: getPosIDs(),
    };
    getFlowOrgTreeRun(deptParams);

    if (detailInfo && detailInfo?.id) {
      getUserRun({
        userPositionID: detailInfo?.assignPositionID,
      });
    }
  }, [detailInfo]);

  // 点击左侧树结构
  const onTreeSelect = (selectedKeys: any, selectedNodes: any, deptType: string) => {
    if (deptType == 'assign') {
      formRef?.setFieldsValue({
        assignDepartmentID: selectedNodes?.attributes?.departmentID,
        assignCompanyID: selectedNodes?.attributes?.companyID,
        assignerID: undefined,
      });
    }
    let userListPayload = commonDeptGetUser([selectedNodes]);
    getUserRun({
      ...userListPayload,
    });
  };

  // 处理树数据
  const orgTreeData = (data: any[]): any[] => {
    return data?.map((item: any) => {
      const name = item?.text;
      const nameLength = name?.length;
      const select = name?.search(treeSearch);
      const searchLength = treeSearch?.length;
      const afterStr = name?.slice(0, select);
      const selectStr = treeSearch;
      const beforeStr = name?.slice(select + searchLength, nameLength);
      const titleTree =
        select > -1 && selectStr ? (
          <span className={pageStyles['over-flow-hidden']}>
            {afterStr}
            <span style={{ color: '#f50' }}>{selectStr}</span>
            {beforeStr}
          </span>
        ) : (
          <span className={pageStyles['over-flow-hidden']}>{item?.text}</span>
        );

      if (item?.children && item?.children?.length > 0) {
        return {
          ...item,
          title: (
            <div
              style={{
                display: 'flex',
                alignItems: 'center',
                paddingRight: 20,
              }}
              id={item?.id}
            >
              {titleTree}
            </div>
          ),
          searchTitle: item?.text,
          key: item?.id,
          value: item?.id,
          disabled: item?.textType == '2' ? false : true,
          // disabled: !item?.pID,
          children: orgTreeData(item?.children),
        };
      }
      return {
        ...item,
        title: (
          <div
            style={{
              display: 'flex',
              alignItems: 'center',
              paddingRight: 20,
            }}
            id={item?.id}
          >
            {titleTree}
          </div>
        ),
        disabled: item?.textType == '2' ? false : true,
        searchTitle: item?.text,
        key: item?.id,
        value: item?.id,
      };
    });
  };

  /**岗位搜索 */
  const assignSearchValue = (data: string) => {
    treeSearchValue(data);
  };

  /**委托人变化 */
  const assignUserChange = (value: string) => {
    changeAssignUser(value);
  };

  return (
    <Fragment>
      <Col span={24}>
        <Form.Item
          label={'委托岗位'}
          name="assignPositionID"
          rules={[
            {
              required: true,
              message: '请选择委托岗位',
            },
          ]}
        >
          <TreeSelect
            placeholder="请选择委托岗位"
            showSearch={true}
            treeNodeFilterProp={'searchTitle'}
            treeData={orgTreeData(getFlowOrgList)}
            onSelect={(selectedKeys, selectedNodes) => {
              onTreeSelect(selectedKeys, selectedNodes, 'assign');
            }}
            onSearch={assignSearchValue}
          />
        </Form.Item>
      </Col>
      <Col span={24}>
        <Form.Item
          label={'委托人'}
          name="assignerID"
          rules={[
            {
              required: true,
              message: '请选择委托人',
            },
          ]}
        >
          <Select placeholder={`请选择委托人`} allowClear={true} loading={getFlowOrgTreeLoading || getUserLoading} onChange={assignUserChange}>
            {getUserList?.map((item: any) => {
              return (
                <Select.Option disabled={item.id == agentUserID ? true : false} value={item?.id} key={item?.id}>
                  <MyIcon style={{ marginRight: 5 }} type="icon-lianxiren" />
                  {item?.realName}
                </Select.Option>
              );
            })}
          </Select>
        </Form.Item>
        <Form.Item
          style={{
            display: 'none',
          }}
          name="assignDepartmentID"
          label=""
        >
          <Input hidden />
        </Form.Item>
        <Form.Item
          style={{
            display: 'none',
          }}
          name="assignCompanyID"
          label=""
        >
          <Input hidden />
        </Form.Item>
      </Col>
    </Fragment>
  );
};
